//  WDGroMoreBannerManager.m
//  WDGroMore
//
//  Created by little People on 2023/7/27.

#import "WDGroMoreBannerManager.h"
#import "WDGroMoreDelegateManager.h"
#import "WDGroMoreJosnManager.h"
#import <BUAdSDK/BUNativeExpressBannerView.h>
#import "WDBMS.h"
@interface WDGroMoreBannerManager ()<BUNativeExpressBannerViewDelegate>

@property (nonatomic, strong) BUNativeExpressBannerView *bannerView;
@property (nonatomic, assign) BOOL bannerShouldLoad;
@property (nonatomic, assign) BOOL topD;
@property (nonatomic, copy) NSString *placementId;
@property (nonatomic, copy) NSString *userId;

@end

@implementation WDGroMoreBannerManager

+ (instancetype)manager {
    static WDGroMoreBannerManager *_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

- (void)createBannerAdWithPlacementId:(NSString *)placementId userId:(NSString *)userId {
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createBannerAdWithPlacementId:placementId userId:userId];
        });
        return;
    }

    self.placementId = placementId;
    self.userId = userId;

    CGSize adSize = CGSizeMake(300, 45);
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *rootVC = keyWindow.rootViewController;
    if (!rootVC) return;

    NSLog(@"[Banner] Creating banner view with placementId: %@", placementId);
    self.bannerView = [[BUNativeExpressBannerView alloc] initWithSlotID:placementId
                                                     rootViewController:rootVC
                                                                  adSize:adSize
                                                                interval:30];
    self.bannerView.frame = [self bannerFrameForPositionTop:self.topD size:adSize];
    self.bannerView.delegate = self;
    [rootVC.view addSubview:self.bannerView];
    self.bannerView.hidden = YES;
    NSLog(@"[Banner] Banner view added to rootVC.view");
    [WDGroMoreTrackManager track:BMS_EVENT_AD_REQUEST params:@{BMS_PARAM_WDS:BMS_WDS_AD_REQUEST} dType:BMS_DTYPE_AD_ACTION desc:BMS_WDS_AD_REQUEST options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (CGRect)bannerFrameForPositionTop:(BOOL)isTop size:(CGSize)size {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    UIViewController *vc = window.rootViewController;
    if (!vc) return CGRectZero;
    CGFloat screenWidth = UIScreen.mainScreen.bounds.size.width;
    CGFloat screenHeight = UIScreen.mainScreen.bounds.size.height;
    CGFloat x = (screenWidth - size.width) / 2.0;
    CGFloat y = isTop ? vc.view.safeAreaInsets.top : (screenHeight - size.height - vc.view.safeAreaInsets.bottom + 20);
    return CGRectMake(x, y, size.width, size.height);
}

- (void)showBannerAdWithTop:(BOOL)top {
    NSLog(@"[Banner] showBannerAdWithTop: %d", top);
    self.bannerShouldLoad = YES;
    self.topD = top;
//    [[WDGroMoreBmsRepoertManager manager] bannerBmsEventWithEventName:BMS_EVENT_ad_button_click bannerAd:self.bannerView];

    if (self.bannerView) {
        self.bannerView.frame = [self bannerFrameForPositionTop:top size:self.bannerView.frame.size];
        [self bannerAdLoadAdData];
    } else {
        [self createBannerAdWithPlacementId:self.placementId userId:self.userId];
        [self bannerAdLoadAdData];
    }
}

- (void)bannerAdLoadAdData {
    if (self.bannerShouldLoad && self.bannerView) {
        self.bannerShouldLoad = NO;
        NSLog(@"[Banner] Loading banner ad data");
//        [[WDGroMoreBmsReportManager manager] bannerBmsEventWithEventName:BMS_EVENT_ad_load_start bannerAd:self.bannerView];
        [self.bannerView loadAdData];
        self.bannerView.hidden = NO;
    }
}

- (void)closeBannerAd {
    NSLog(@"[Banner] Closing banner ad");
    [self.bannerView removeFromSuperview];
    self.bannerView.delegate = nil;
    self.bannerView = nil;
}

- (void)destroyBannerView {
    NSLog(@"[Banner] Destroying banner view");
    [self.bannerView removeFromSuperview];
    self.bannerView.delegate = nil;
    self.bannerView = nil;
}

#pragma mark - BUNativeExpressBannerViewDelegate

- (void)nativeExpressBannerAdViewDidLoad:(BUNativeExpressBannerView *)bannerAdView {
    NSLog(@"[Banner] Banner ad loaded successfully");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:bannerAdView];
    [WDGroMoreTrackManager track:BMS_EVENT_AD_FILL
                          params:@{BMS_PARAM_WDS:BMS_WDS_AD_FILL,
                                   BMS_PARAM_TAB1:ritInfo[@"adn"] ?: @"",
                                   BMS_PARAM_TAB2:ritInfo[@"slotID"] ?: @"",
                                   BMS_PARAM_TAB3:ritInfo[@"ecpm"] ?: @""}
                           dType:BMS_DTYPE_AD_ACTION
                            desc:BMS_WDS_AD_FILL
                         options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
//    [[WDGroMoreBmsReportManager manager] bannerBmsEventWithEventName:BMS_EVENT_ad_show_start bannerAd:bannerAdView];
    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreBannerAdShow:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreBannerAdShow:bannerAdView];
    }
}

- (void)nativeExpressBannerAdView:(BUNativeExpressBannerView *)bannerAdView didLoadFailWithError:(NSError *_Nullable)error {
    NSLog(@"[Banner] Failed to load banner ad: %@", error);
    NSLog(@"[Banner] Error message: %@", error.userInfo[@"message"]);
}

- (void)nativeExpressBannerAdViewDidClick:(BUNativeExpressBannerView *)bannerAdView {
    NSLog(@"[Banner] Banner ad clicked");
    NSDictionary *ritInfo = [WDGroMoreAdHelper ecpmInfoFromAd:bannerAdView];

    NSString *adn = ritInfo[@"adn"] ?: @"";
    NSString *ecpm = ritInfo[@"ecpm"] ?: @"";
    NSString *slotID = ritInfo[@"slotID"] ?: @"";

    [WDGroMoreTrackManager track:BMS_EVENT_AD_CLICK params:@{BMS_PARAM_WDS:BMS_WDS_AD_CLICK,BMS_PARAM_TAB1:adn,BMS_PARAM_TAB2:slotID,BMS_PARAM_TAB3:ecpm} dType:BMS_DTYPE_AD_ACTION desc:BMS_WDS_AD_CLICK options:[WDGroMoreTrackManager trackOptionsOnlySendBMS]];
}

- (void)nativeExpressBannerAdViewDidRemoved:(BUNativeExpressBannerView *)bannerAdView {
    NSLog(@"[Banner] Banner ad removed");
//    [[WDGroMoreBmsReportManager manager] bannerBmsEventWithEventName:BMS_EVENT_ad_show_end bannerAd:bannerAdView];
    [self destroyBannerView];
    [self createBannerAdWithPlacementId:self.placementId userId:self.userId];
    [self bannerAdLoadAdData];

    if ([WDGroMoreDelegateManager manager].delegate &&
        [[WDGroMoreDelegateManager manager].delegate respondsToSelector:@selector(WDGroMoreBannerAdDelegateWithClose:)]) {
        [[WDGroMoreDelegateManager manager].delegate WDGroMoreBannerAdDelegateWithClose:bannerAdView];
    }
}

@end
